package cn.itcast.service.impl;

import cn.itcast.dao.OrderDao;
import cn.itcast.dao.SetmealDao;
import cn.itcast.entity.OrderQueryPageBean;
import cn.itcast.entity.PageResult;
import cn.itcast.pojo.*;
import cn.itcast.service.OrderService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import cn.itcast.dao.PayDao;
import cn.itcast.constant.MessageConstant;
import cn.itcast.dao.MemberDao;
import cn.itcast.dao.OrderDao;
import cn.itcast.dao.OrderSettingDao;
import cn.itcast.entity.Result;
import cn.itcast.pojo.Order;
import cn.itcast.service.OrderService;
import cn.itcast.util.IdWorker;
import cn.itcast.utils.DateUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private IdWorker idWorker;

    @Override
    public PageResult findPage(OrderQueryPageBean orderQueryPageBean) {
        PageHelper.startPage(orderQueryPageBean.getCurrentPage(), orderQueryPageBean.getPageSize());
        Page<Order> page = orderDao.findPage(orderQueryPageBean);
        for (Order order : page) {
            Integer id = order.getSetmealId();
            Setmeal setmeal = setmealDao.findById(id);
            if (!ObjectUtils.isEmpty(id)) {
                order.setSetmealName(setmeal.getName());
            }
            order.setSetmeal(setmeal);

        }
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public boolean submitOrder(Order order) {
        try {
            return orderDao.submitOrder(order);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean saveOrder(Order order) {
        try {
            order.setId(UUID.randomUUID().toString());
            return orderDao.saveOrder(order);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Order findOrderById(String id) {
        try {
            Order order = orderDao.findOrderById(id);
            if (!ObjectUtils.isEmpty(order)) {
                return order;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean updateArrival(String id, Integer arrival) {
        try {
            return orderDao.updateArrival(id, arrival);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 预约支付查询
     */

    @Override
    public List<Integer> findOrderCountByMonths(List<String> months) {
        List<Integer> orderCount = new ArrayList<>();
        for (String month : months) {
            String startDate = month + ".01";
            String endDate = month + ".31";
            Integer count = orderDao.findOrderCountAfterDates(startDate, endDate);
            orderCount.add(count);
        }
        return orderCount;
    }

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /*
     *
     * 校验手机短信验证码
     * */
    @Override
    public Boolean checkCode(String phone, String validateCode) {

        /*
         * 预约的手机短信验证码
         * */
        String rediskey = "REDIS_KEY_YUYUE" + phone;
        //从redis中取出验证码
        String redisCode = redisTemplate.opsForValue().get(rediskey);
        //校验验证码
        if (!StringUtils.equals(redisCode, validateCode)) {
            //不一致,则返回空
            return null;
        }
        //如果一致要把redis中的验证码给删除掉
        //redisTemplate.delete(rediskey);

        return true;
    }

    /*
     *
     * 保存预约信息
     * */

    @Override
    public Result saveOrder(Map map) throws Exception {

        //1.检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        String orderDate = (String) map.get("orderDate");
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));

        if (null == orderSetting) {
            //指定日期没有进行预约设置，无法完成体检预约
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);

        }

        //2.检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
        int number = orderSetting.getNumber(); //可预约人数
        int reservations = orderSetting.getReservations(); //已预约人数
        if (reservations >= number) {

            //已经约满无法预约
            return new Result(false, MessageConstant.ORDER_FULL);

        }

        //3.检查用户是否重复预约，如果重复预约则无法完成再次预约

        //3.1先判断是否为会员
        String phoneNumber = (String) map.get("phoneNumber"); //获取用户页面输入的手机号
        Member member = memberDao.findByphoneNumber(phoneNumber);
        if (null != member) {
            //判断是否再重复预约
            Integer memberId = member.getId();  //会员ID
            Date order_Date = DateUtils.parseString2Date(orderDate);//预约日期
            String setmealId = (String) map.get("setmealId");  //套餐ID

            Order order = new Order(memberId, order_Date, Integer.parseInt(setmealId));
            //根据条件进行查询
            List<Order> list = orderDao.findByCondition(order);

            if (list != null && list.size() > 0) {
                //说明用户在重复预约，无法完成再次预约
                return new Result(false, MessageConstant.HAS_ORDERED);

            }
        } else {
            //4.检查当前用户是否为会员，如果是会员直接完成预约，如果不是会员则自动完成注册并进行预约
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(phoneNumber);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());

            //完成自动注册
            memberDao.saveMember(member);
        }
        //5.预约成功，更新当日的已预约的人数
        Order order = new Order();
        //生成微信支付订单号

        order.setId(idWorker.nextId() + "");
        order.setMemberId(member.getId());//设置会员ID
        order.setOrderDate(DateUtils.parseString2Date(orderDate));  //设置预约日期
        order.setOrderType((String) map.get("orderType")); //设置预约类型
        order.setOrderStatus(0); //预约状态
        String setmealId = map.get("setmealId") + "";
        order.setSetmealId(Integer.parseInt(setmealId)); //套餐I
        order.setArrival(0); //预约是否到诊
        order.setPhoneNumber(phoneNumber); //电话
        order.setName((String) map.get("name"));
        order.setIdCard((String) map.get("idCard"));
        order.setSex((String) map.get("sex"));
        Integer addressId = (Integer) map.get("addressId");
        order.setAddressId(addressId);
        order.setPayStatus(0);  //支付状态
        orderDao.add(order);

        orderSetting.setReservations(orderSetting.getReservations() + 1); //设置预约人数加1

        orderSettingDao.editReservationsByOrderDate(orderSetting);

        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());
    }

    @Override
    public Order findById(String id) {

        return orderDao.findById(id);
    }

}
